package com.jieshuibao.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;

import com.jieshuibao.common.config.Const;
import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.mapper.CompanyMapper;
import com.jieshuibao.mapper.QuestionUserMapper;
import com.jieshuibao.mapper.RewardFlowJsbMapper;
import com.jieshuibao.mapper.SecretlyMapper;
import com.jieshuibao.mapper.UserCompanyMapper;
import com.jieshuibao.mapper.UserDealRecordExMapper;
import com.jieshuibao.mapper.UserDealRecordMapper;
import com.jieshuibao.mapper.UserExMapper;
import com.jieshuibao.mapper.UserMapper;
import com.jieshuibao.model.db.Category;
import com.jieshuibao.model.db.Company;
import com.jieshuibao.model.db.Counselor;
import com.jieshuibao.model.db.Level;
import com.jieshuibao.model.db.QuestionUserKey;
import com.jieshuibao.model.db.QuestionUserOwnMsg;
import com.jieshuibao.model.db.Secretly;
import com.jieshuibao.model.db.User;
import com.jieshuibao.model.db.UserDealRecord;
import com.jieshuibao.model.db.UserExample;
import com.jieshuibao.model.db.UserSearch;
import com.jieshuibao.model.domain.Integrals;
import com.jieshuibao.model.domain.LoginResponse;
import com.jieshuibao.model.domain.PagePhone;
import com.jieshuibao.model.domain.UserDetails;
import com.jieshuibao.util.PayTypeUtil;
import com.jieshuibao.util.StringUtils;
import com.jieshuibao.util.UUIDGenerator;
import com.jieshuibao.wx.util.PayCommonUtil;

@Service
public class UserService {

	@Resource
	private UserMapper userMapper;

	@Resource
	private UserExMapper userExMapper;

	@Resource
	private UserCompanyMapper userCompanyMapper;

	@Resource
	private QuestionUserMapper questionUserMapper;

	@Resource
	private SecretlyMapper secretlyMapper;

	@Resource
	private RewardFlowJsbMapper rewardFlowJsbMapper;

	@Resource
	private UserDealRecordExMapper userDealRecordExMapper;

	@Resource
	private UserDealRecordMapper userDealRecordMapper;

	@Resource
	private CompanyMapper companyMapper;

	@Resource
	private CounselorDutyService counselorDutyService;
	
	@Resource
	private CategoryService categoryService;
	

	@Resource
	private IntegralService IntegralService;
	
	public QuestionUserOwnMsg getUserMsgByPhoneNum(String phoneNumber){
		 return userMapper.selectUserMsgByPhoneNum(phoneNumber);
	}
	
	public void addUser(User user) {
		userMapper.insertSelective(user);
	}

	public void delUserByPhoneNumber(String phoneNumber) {
		userMapper.deleteByPrimaryKey(phoneNumber);
	}

	public void updateUser(User user) {
		userMapper.updateByPrimaryKeySelective(user);
	}

	public void updateUserByExample(User user, UserExample userExample) {
		userMapper.updateByExampleSelective(user, userExample);
	}

	public User getUserByPhoneNumber(String phoneNumber) {
		return userMapper.selectByPrimaryKey(phoneNumber);
	}

	public List<User> getPageUser(UserExample userExample) {
		return userMapper.selectPage(userExample);
	}

	public int countUser(UserExample userExample) {
		return userMapper.countByExample(userExample);
	}

	public List<User> selectByExample(UserExample userExample) {
		return userMapper.selectByExample(userExample);
	}

	public List<User> getUserByExample(UserExample userExample) {
		return userCompanyMapper.selectCompanyUserByExample(userExample);
	}

	public void updateUserAndUser(User user, User user1) {
		if (user != null) {

			userMapper.updateByPrimaryKeySelective(user);
		}
		if (user1 != null) {
			userMapper.updateByPrimaryKeySelective(user1);
		}
	}

	/**
	 * 
	 * @param user
	 *            偷看着
	 * @param user1
	 *            公开问题者
	 * @param user2
	 *            回答者
	 * @param questionUserKey1
	 * @param questionUserKey2
	 * @param secretly
	 * @param userDealRecords
	 */
	public void updateUserAndUserQuestionUserKey(User user, User user1,
			User user2, QuestionUserKey questionUserKey1,
			QuestionUserKey questionUserKey2, Secretly secretly,
			List<UserDealRecord> userDealRecords) {

		if (user != null) {

			userMapper.updateByPrimaryKeySelective(user);
		}
		if (user1 != null) {
			userMapper.updateByPrimaryKeySelective(user1);
		}
		if (user2 != null) {
			userMapper.updateByPrimaryKeySelective(user2);
		}
		// 记录偷看（用户 和数量）
		if (questionUserKey1 == null) {
			questionUserMapper.insertSelective(questionUserKey2);

		}
		if (secretly != null) {
			secretlyMapper.insertSelective(secretly);
		}
		for (UserDealRecord userDealRecord : userDealRecords) {
			userDealRecordMapper.insertSelective(userDealRecord);
		}

	}

	// 添加员工
	public void updateUserAndCompany(User user, Company company, double money) {
		if (company != null) {
			/*
			 * UserDealRecord userDealRecord1 = new UserDealRecord();
			 * UserDealRecord userDealRecord2 = new UserDealRecord(); Date date
			 * = new Date();
			 * 
			 * String uuid1 = UUIDGenerator.getUUID();//用户支出 String uuid2 =
			 * UUIDGenerator.getUUID();//企业收入 userDealRecord1.setUuid(uuid1);
			 * userDealRecord1.setAccountType(PayTypeUtil.ACCOUNTTYPE_PERSONAL);
			 * userDealRecord1.setBusinessNo(user.getPhoneNumber());
			 * userDealRecord1.setCreateDate(date);
			 * userDealRecord1.setGoodsType(PayTypeUtil.GOODSTYPE_VIPCARD);
			 * userDealRecord1.setPaySucTime(date);
			 * userDealRecord1.setPayType(PayTypeUtil.PAYTYPE_VIPBALANCE);
			 * userDealRecord1.setRealPrice(money);
			 * userDealRecord1.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
			 * userDealRecord1.setSum(money);
			 * userDealRecord1.setTradeType(PayTypeUtil.TRDETYPE_EXPENDITURE);
			 * userDealRecord1.setUserId(user.getPhoneNumber());
			 * 
			 * userDealRecord2.setUuid(uuid2);
			 * userDealRecord2.setAccountType(PayTypeUtil.ACCOUNTTYPE_BUSINESS);
			 * userDealRecord2.setBusinessNo(user.getPhoneNumber());
			 * userDealRecord2.setCreateDate(date);
			 * userDealRecord2.setGoodsType(PayTypeUtil.GOODSTYPE_VIPCARD);
			 * userDealRecord2.setPaySucTime(date);
			 * userDealRecord2.setPayType(PayTypeUtil.PAYTYPE_VIPBALANCE);
			 * userDealRecord2.setRealPrice(money);
			 * userDealRecord2.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
			 * userDealRecord2.setSum(money);
			 * userDealRecord2.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
			 * userDealRecord2.setUserId(company.getUuid());
			 * userDealRecordMapper.insertSelective(userDealRecord1);
			 * userDealRecordMapper.insertSelective(userDealRecord2);
			 */
			companyMapper.updateByPrimaryKeySelective(company);
		}

		if (user != null) {
			userMapper.updateByPrimaryKeySelective(user);
		}

	}

	// 内购
	public void updateUserWithin(User user, double money) {
		if (user != null && money > 0) {
			String uuid1 = UUIDGenerator.getUUID();
			UserDealRecord userDealRecord1 = new UserDealRecord();
			Date date = new Date();
			String phoneNumber = user.getPhoneNumber();

			userDealRecord1.setUuid(uuid1);
			userDealRecord1.setAccountType(PayTypeUtil.ACCOUNTTYPE_PERSONAL);
			userDealRecord1.setBusinessNo(phoneNumber);
			userDealRecord1.setCreateDate(date);
			userDealRecord1.setGoodsType(PayTypeUtil.GOODSTYPE_WITHIN);
			userDealRecord1.setPaySucTime(date);
			userDealRecord1.setPayType(PayTypeUtil.PAYTYPE_WITHIN);
			userDealRecord1.setRealPrice(money);
			userDealRecord1.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
			userDealRecord1.setSum(money);
			userDealRecord1.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
			userDealRecord1.setUserId(phoneNumber);
			userDealRecordMapper.insertSelective(userDealRecord1);
			userMapper.updateByPrimaryKeySelective(user);

		}

	}

	// 搜索
	public List<UserSearch> getUserSearch(PagePhone pagePhone) {
		return userExMapper.selectSearchUser(pagePhone);
	}

	// 查咨询师的级别
	public Level getLevelMoney(String phone) {
		return userExMapper.selectLevelName(phone);
	}

	// 个人主页
	public UserDetails getPersonalUser(String phone) {
		return userExMapper.selectPersonalUser(phone);
	}

	// 根据用户账号查找咨询师信息
	public Counselor getCounselorByPhoneNumber(String phone) {
		return userExMapper.selectCounseleorByPhone(phone);
	}

	// 根据真实手机号查询用户信息
	public User getUserByphone(String phone) {
		List<User> list = userExMapper.selectUserByPhone(phone);
		if (list.size()>0) {
			return list.get(0);
		}
		return null;
	}
	/**
	 * 根据手机号查找用户信息 并判断账号是否异常
	 * @param phone
	 * @return
	 */
	public BaseRes<User> getWxUserByphone(String phone) {
		List<User> list = userExMapper.selectUserByPhone(phone);
		BaseRes<User> res = new BaseRes<User>();
		int size = list.size();
		if (size>1) {
			res.setCode(BaseRes.FAIL_CODE);
			res.setDes("账号异常请联系管理员");
			return res;
		}else if(size==1){
			User user = list.get(0);
			Integer role = user.getRole();
			if (role==null||role==Const.USER_ROLE_0) {
				res.setCode(BaseRes.FAIL_CODE);
				res.setDes("账号异常请联系管理员");
				return res;
			}
			res.setCode(BaseRes.SUCCESS_CODE);
			res.setDes(BaseRes.SUCCESS_DES);
			res.setData(list.get(0));
			return res;
		}else {
			return null;
		}
		
	}
	/**
	 * 用户信息
	 */
	public LoginResponse  userInformation(String  userId){
		LoginResponse loginResponse = new LoginResponse();
		try {
			User user = userMapper.selectByPrimaryKey(userId);
			Counselor counselor = userExMapper.selectCounseleorByPhone(userId);
			if (user!=null) {
				
				if (user.getSex() == null) {
					loginResponse.setGender("男");
				} else if (user.getSex() == 2) {
					loginResponse.setGender("女");
				} else {
					loginResponse.setGender("男");
				}
				if (user.getBirthdayDate() != null) {
					SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");
					String format = dateFormater.format(user.getBirthdayDate());
					
					loginResponse.setBirthday(format);
							
				}
				String counselorDuty = user.getCounselorDuty();
				if (StringUtils.isNotBlank(counselorDuty)) {
					
					String counselorDutyName = counselorDutyService.getCounselorDutyName(counselorDuty);
					user.setCounselorDuty(counselorDutyName);
					BeanUtils.copyProperties(loginResponse,
							user);
				}
				String companyUuid = user.getCompanyUuid();
				Company company = companyMapper.selectByPrimaryKey(companyUuid);
				
				if(company!=null){
					loginResponse.setCompanyLog(company.getCompanyLog());
					loginResponse.setBusinessBalance(company.getBusinessBalance());
					loginResponse.setCompanyStataus(company.getStatus());
				}
				Integrals integrals = IntegralService.getIntegralsByUuid(userId);
				if (integrals==null) {
					loginResponse.setIntegralScore(0);
				}else {
					int integralSum = integrals.getIntegralSum();
					loginResponse.setIntegralScore(integralSum);
				}
			}
			if (counselor != null) {
				Date applyDate = counselor.getApplyDate();
						
				if (applyDate != null) {
					loginResponse.setApplyTime(applyDate);
							
				}
				String counselorLevel = counselor.getCounselorLevel();
						

				if (counselorLevel != null
						&& !counselorLevel.equals("")) {
					Level level = userExMapper.selectLevelName(userId);
					loginResponse.setLevelName(level.getName());
					loginResponse.setLevelMoney(level.getMoney());
							
				}

				String adept = counselor.getAdept();
				if (adept != null && !adept.equals("")) {
					String[] adeps = adept.split(",");
					HashMap<String, String> map = new HashMap<String, String>();
					for (String categoyrUuid : adeps) {
						if (categoyrUuid != null) {
							Category categoryById = categoryService.getCategoryById(categoyrUuid);
									
							if (categoryById != null) {
								map.put(categoyrUuid,categoryById.getName());
												
							}
						}
					}
					loginResponse.setAdepts(map);
				}
				BeanUtils.copyProperties(loginResponse,
						counselor);
			}
			
			
			
			
			return loginResponse;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} 
		
	}

	/**
	 * <<<<<<< HEAD 修改用户的咨询次数视频次余额
	 */
	public void updateUserAvisoryNumAndBalance(User user) {
		userExMapper.updateUserAdvisoryNum(user);
	}

	/**
	 * 修改用户余额
	 * 
	 * @param userid
	 *            用户id
	 * @param money
	 *            要修改后的余额
	 */
	public void updateBalance(String userid, Double money) {
		User user = new User();
		user.setPhoneNumber(userid);
		user.setBalance(money);
		userMapper.updateByPrimaryKeySelective(user);
	}

	/**
	 * 是否是视频会员
	 * 
	 * @param userid
	 * @return
	 */
	public boolean isVideoVip(String userid) {
		User user = userMapper.selectByPrimaryKey(userid);
		if (null == user) {
			return false;
		}
		Date videoVipInvalidTime = user.getVideoVipInvalidTime();
		Date now = new Date();
		if (null != videoVipInvalidTime && videoVipInvalidTime.after(now)) {
			return true;
		}
		return false;
	}
	/**
	 * 用户是否完善信息
	 * @param userId
	 * @return
	 */
	public boolean isCompleteUser(String userId) {
		User user = userMapper.selectByPrimaryKey(userId);
		if (null == user) {
			return false;
		}
		String realName = user.getRealName();
		String userName = user.getUserName();
		String address = user.getAddress();
		String companyName = user.getCompanyName();
		if (StringUtils.isBlank(realName) || StringUtils.isBlank(userName)
				|| StringUtils.isBlank(address)
				|| StringUtils.isBlank(companyName)) {
			return false;
		}
		return true;
	}
	/**
	 * 修改用户问答卡余额或用户渠道
	 * @param user
	 */
	public int updateUserQACardBlance(User user) {
		return userExMapper.updateUserQACardBlance(user);
	}
}
